package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shopping_07_28/api/request"
	"shopping_07_28/internal/model"
	"shopping_07_28/pkg"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUser
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user.Mobile = req.Mobile

	err := user.GetMobileByUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		Name:     req.Name,
	}

	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": nil,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUser
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user.Mobile = req.Mobile

	err := user.GetMobileByUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登陆失败",
			"data": nil,
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": nil,
	})

}
